<?php
namespace Home\Controller;

use Common\Controller\HomeController;
use Think\Page;

class PriceController extends HomeController
{
    /**
     * 价格列表
     * @author Mr.Alien
     * @param int $p 页数
     * @return string
     */
    public function index($p=1)
    {
        $where['user_id'] = session('id');
        $template_name_list = M('Price')->where($where)->field("distinct template_name")->select();
        $this->listRows = 10;
        if(I("get.template_name")){
            $this->where['template_name'] = I('get.template_name');
        }else{
            $template_name_list && ($this->where['template_name'] = $template_name_list[0]['template_name']);
        }
        I('get.name') && ($this->where['name'] = I('get.name'));
        $this->where['user_id'] = session('id');
        $list = D(CONTROLLER_NAME)->relation(true)->where($this->where)->page($p,$this->listRows)->order($this->order)->select();
        $page = new Page(D(CONTROLLER_NAME)->where($this->where)->count(),$this->listRows);
        $this->assign('template_name_list',$template_name_list);
        $this->assign('list',json_encode($list));
        $this->assign('page',$page->show());
        $this->display();
    }

    /**
     * 保存价格
     * @author Mr.Alien
     * @return string
     */
    public function save()
    {
        $data = I("post.");
        $res = M('Price')->save($data);
        if($res === false){
            $this->error('保存失败');
        }else{
            $this->success('保存成功');
        }
    }

    /**
     * 设置模板价格
     * @author Mr.Alien
     * @return string
     */
    public function setName()
    {
        $name = I('post.name');
        $has = M('Price')->where(array('user_id'=>session('id'),'template_name'=>$name))->find();
        $has && $this->error('已有此模板');
        $province = M('Address')->where(array('level'=>2))->select();
        $list  = array();
        foreach($province as $key => $value) {
            $list['province_id'] = $value['id'];
            $list['name'] = $value['name'];
            $list['user_id'] = session('id');
            $list['template_name'] = $name;
            M('Price')->add($list);
        }
        $this->success('保存成功');
    }
}